<template>
    <div class="approve-book-page">
        <el-card>
            <h2 style="text-align: center; margin-bottom: 24px">
                册子信息审批
            </h2>
            <div
                style="
                    display: flex;
                    gap: 16px;
                    align-items: center;
                    margin-bottom: 16px;
                "
            >
                <el-input
                    v-model="searchName"
                    placeholder="搜索角色名称"
                    clearable
                    style="width: 200px"
                />
                <el-select
                    v-model="filterStatus"
                    placeholder="筛选状态"
                    clearable
                    style="width: 150px"
                >
                    <el-option label="全部" value="" />
                    <el-option label="待审批" value="待审批" />
                    <el-option label="已通过" value="已通过" />
                    <el-option label="未通过" value="未通过" />
                </el-select>
            </div>
            <el-table :data="pagedBooks" class="book-table">
                <!-- 名称 -->
                <el-table-column prop="name" label="名称" width="120" />
                <!-- 头像预览 -->
                <el-table-column prop="avatar" label="头像" width="100">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.avatar"
                            :src="scope.row.avatar"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.avatar]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <!-- 书本封面正面预览 -->
                <el-table-column
                    prop="bookfront1"
                    label="书本封面正面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookfront1"
                            :src="scope.row.bookfront1"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookfront1]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <!-- 书本封面背面预览 -->
                <el-table-column
                    prop="bookfront2"
                    label="书本封面背面"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookfront2"
                            :src="scope.row.bookfront2"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookfront2]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <!-- 内容页正面预览 -->
                <el-table-column
                    prop="bookPage1"
                    label="书本内容页正面背景图"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookPage1"
                            :src="scope.row.bookPage1"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookPage1]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <!-- 内容页背面预览 -->
                <el-table-column
                    prop="bookPage2"
                    label="书本内容页背面背景图"
                    width="100"
                >
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookPage2"
                            :src="scope.row.bookPage2"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookPage2]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <!-- 书本封底预览 -->
                <el-table-column prop="bookBack" label="书本封底" width="100">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.bookBack"
                            :src="scope.row.bookBack"
                            style="width: 3rem; height: 3rem"
                            fit="contain"
                            :preview-src-list="[scope.row.bookBack]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <!-- 审批状态 -->
                <el-table-column prop="status" label="审批状态" width="120">
                    <template #default="scope">
                        <el-tag
                            :type="
                                scope.row.status === '已通过'
                                    ? 'success'
                                    : scope.row.status === '未通过'
                                    ? 'danger'
                                    : 'info'
                            "
                        >
                            {{ scope.row.status || "待审批" }}
                        </el-tag>
                    </template>
                </el-table-column>
                <!-- 审批说明 -->
                <el-table-column prop="remark" label="审批说明" width="180" />
                <!-- 操作（可根据实际需求调整） -->
                <el-table-column label="操作" width="80">
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="success"
                            @click="openApproveEdit(scope.row)"
                            :disabled="
                                scope.row.status === '未通过' ||
                                scope.row.status === '已通过'
                            "
                            round
                            >通过</el-button
                        >
                        <el-button
                            size="small"
                            type="danger"
                            @click="openApprove(scope.row, '未通过')"
                            :disabled="
                                scope.row.status === '未通过' ||
                                scope.row.status === '已通过'
                            "
                            round
                            >拒绝</el-button
                        >
                        <el-popconfirm
                            title="确定删除该申请吗？"
                            @confirm="handleDelete(scope.row)"
                            confirm-button-text="删除"
                            cancel-button-text="取消"
                        >
                            <template #reference>
                                <el-button size="small" type="warning" round
                                    >删除</el-button
                                >
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; margin: 24px 0">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :page-size="pageSize"
                    :total="books.length"
                    v-model:current-page="currentPage"
                />
            </div>
        </el-card>
        <!-- 编辑对话框，布局与主表单一致 -->
        <el-dialog
            v-model="showApproveEditDialog"
            title="编辑书本申请"
            width="1100px"
            center
        >
            <el-form :model="approveEditForm" label-width="140px">
                <el-row :gutter="40">
                    <el-col :span="12">
                        <el-form-item label="角色名称">
                            <el-input
                                v-model="approveEditForm.name"
                                :readonly="true"
                                disabled
                            />
                        </el-form-item>
                        <el-form-item label="简介">
                            <el-input
                                v-model="approveEditForm.desc"
                                disabled
                                type="textarea"
                                rows="4"
                            />
                        </el-form-item>
                        <el-form-item label="是否显示头像">
                            <el-switch
                                disabled
                                v-model="approveEditForm.isAvatar"
                            />
                        </el-form-item>
                        <el-form-item label="头像链接">
                            <el-input
                                disabled
                                v-model="approveEditForm.avatar"
                            />
                            <el-image
                                v-if="approveEditForm.avatar"
                                :src="approveEditForm.avatar"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[approveEditForm.avatar]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封面正面">
                            <el-input
                                disabled
                                v-model="approveEditForm.bookfront1"
                            />
                            <el-image
                                v-if="approveEditForm.bookfront1"
                                :src="approveEditForm.bookfront1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[approveEditForm.bookfront1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封面背面">
                            <el-input
                                disabled
                                v-model="approveEditForm.bookfront2"
                            />
                            <el-image
                                v-if="approveEditForm.bookfront2"
                                :src="approveEditForm.bookfront2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[approveEditForm.bookfront2]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="内容页正面背景图">
                            <el-input
                                disabled
                                v-model="approveEditForm.bookPage1"
                            />
                            <el-image
                                v-if="approveEditForm.bookPage1"
                                :src="approveEditForm.bookPage1"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[approveEditForm.bookPage1]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="内容页背面背景图">
                            <el-input
                                disabled
                                v-model="approveEditForm.bookPage2"
                            />
                            <el-image
                                v-if="approveEditForm.bookPage2"
                                :src="approveEditForm.bookPage2"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[approveEditForm.bookPage2]"
                                preview-teleported
                            />
                        </el-form-item>
                        <el-form-item label="书本封底">
                            <el-input
                                disabled
                                v-model="approveEditForm.bookBack"
                            />
                            <el-image
                                v-if="approveEditForm.bookBack"
                                :src="approveEditForm.bookBack"
                                style="
                                    width: 4rem;
                                    height: 6rem;
                                    margin-top: 8px;
                                "
                                fit="contain"
                                :preview-src-list="[approveEditForm.bookBack]"
                                preview-teleported
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="40">
                    <!-- ...补充数据... -->
                    <el-col :span="12">
                        <!-- 旋转Y -->
                        <el-form-item label="旋转Y">
                            <el-input-number
                                v-model="approveEditForm.rotateY"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                        <!-- 旋转X -->
                        <el-form-item label="旋转X">
                            <el-input-number
                                v-model="approveEditForm.rotateX"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                        <!-- 打开方向 -->
                        <el-form-item label="打开方向">
                            <el-select
                                v-model="approveEditForm.transformOrigin"
                                placeholder="请选择打开方向"
                            >
                                <el-option
                                    label="向左打开"
                                    value="left center"
                                />
                                <el-option
                                    label="向右打开"
                                    value="right center"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 书本文字颜色 -->
                        <el-form-item label="文字颜色">
                            <el-color-picker v-model="approveEditForm.color" />
                        </el-form-item>
                        <!-- 头像位置Top -->
                        <el-form-item label="头像Top">
                            <el-input-number
                                v-model="approveEditForm.avatarTop"
                                :min="0"
                                :max="100"
                            />
                        </el-form-item>
                        <!-- 头像位置Left -->
                        <el-form-item label="头像Left">
                            <el-input-number
                                v-model="approveEditForm.avatarLeft"
                                :min="0"
                                :max="100"
                            />
                        </el-form-item>
                        <el-form-item label="图层(Layers)">
                            <el-input-number
                                v-model="approveEditForm.Layers"
                                :min="0"
                                :max="9999"
                                :step="1"
                                placeholder="请输入图层数"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 旋转Y -->
                        <el-form-item label="书本离顶部的距离">
                            <el-input-number
                                v-model="approveEditForm.bookTop"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                        <!-- 旋转X -->
                        <el-form-item label="书本离左侧的距离">
                            <el-input-number
                                v-model="approveEditForm.bookLeft"
                                :min="0"
                                :max="360"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 编辑对话框 essay部分，布局同主表单 -->
                <el-form-item label="书本内容" class="essay-form-item">
                    <div
                        v-for="(page, pageIdx) in approveEditForm.essay"
                        :key="pageIdx"
                        class="essay-page-block"
                    >
                        <el-divider>第{{ pageIdx + 1 }}组页</el-divider>
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <el-form-item label="页码">
                                    <el-input
                                        disabled
                                        v-model="page.PagesNumeStr"
                                        style="width: 400px"
                                        readonly
                                        placeholder="自动生成"
                                        @change="
                                            (val) =>
                                                handleEditPagesNumeChange(
                                                    page,
                                                    val
                                                )
                                        "
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <div class="essay-content-title">正面内容</div>
                                <div
                                    v-for="(item, idx) in page.frontContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            disabled
                                            v-model="item.text"
                                            type="textarea"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            disabled
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div class="essay-content-title">背面内容</div>
                                <div
                                    v-for="(item, idx) in page.backContent"
                                    :key="idx"
                                    class="essay-content-row"
                                >
                                    <template v-if="item.type === 'text'">
                                        <el-input
                                            disabled
                                            v-model="item.text"
                                            type="textarea"
                                            placeholder="文本内容"
                                            style="width: 400px"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            disabled
                                            v-model="item.Image"
                                            placeholder="图片链接"
                                            style="width: 400px"
                                        />
                                        <el-image
                                            v-if="item.Image"
                                            :src="item.Image"
                                            style="
                                                width: 4rem;
                                                height: 6rem;
                                                margin-top: 8px;
                                            "
                                            fit="contain"
                                            :preview-src-list="[item.Image]"
                                            preview-teleported
                                        />
                                    </template>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showApproveEditDialog = false"
                    >取消</el-button
                >
                <el-button
                    type="primary"
                    @click="handleApproveAndAddBook"
                    :loading="approveEditLoading"
                    >确定</el-button
                >
            </template>
        </el-dialog>
        <!-- 审批对话框 -->
        <el-dialog v-model="showDialog" title="审批说明" width="500px" center>
            <el-form>
                <el-form-item label="审批说明">
                    <el-input
                        v-model="remark"
                        type="textarea"
                        placeholder="请输入审批说明"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showDialog = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleApprove"
                    :loading="loading"
                    >确定</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { BASE_URL } from "../config/http.js";

const books = ref([]);
const searchName = ref("");
const filterStatus = ref("");
const currentPage = ref(1);
const pageSize = 5;

const filteredBooks = computed(() => {
    return books.value.filter((item) => {
        const matchName = searchName.value
            ? (item.name || "").includes(searchName.value)
            : true;
        const matchStatus = filterStatus.value
            ? item.status === filterStatus.value
            : true;
        return matchName && matchStatus;
    });
});
const pagedBooks = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return filteredBooks.value.slice(start, start + pageSize);
});

const showApproveEditDialog = ref(false);
const approveEditForm = reactive({});
const approveEditLoading = ref(false);
let approveRowId = "";
const showDialog = ref(false);
const remark = ref("");
const loading = ref(false);
const approveRow = ref(null);
const approveStatus = ref("");
const operatorId = sessionStorage.getItem("user_id");
const token = sessionStorage.getItem("token");

// 获取全部书本申请
function fetchBooks() {
    axios
        .get(`${BASE_URL}/api/approveBook/`, {
            headers: { Authorization: "Bearer " + token },
        })
        .then((res) => {
            books.value = res.data;
            currentPage.value = 1;
        });
}

// 打开审批弹窗
function openApprove(row, status) {
    approveRow.value = row;
    approveStatus.value = status;
    remark.value = "";
    showDialog.value = true;
}

function openApproveEdit(row) {
    // 清空所有属性
    Object.keys(approveEditForm).forEach((k) => delete approveEditForm[k]);
    // 复制新数据
    Object.assign(approveEditForm, row);
    // 补全每个页组的 PagesNumeStr 字段
    if (approveEditForm.essay && Array.isArray(approveEditForm.essay)) {
        approveEditForm.essay.forEach((page) => {
            page.PagesNumeStr = (page.PagesNume || []).join(",");
        });
    }
    approveRowId = row._id;
    showApproveEditDialog.value = true;
}
// 判断编辑对话框 essay 内容添加按钮是否禁用
function isEditEssayContentDisabled(arr) {
    if (!arr || arr.length === 0) return false;
    if (["img2", "img3"].includes(arr[0].type)) return true;
    return arr.length >= 3;
}
async function handleApproveAndAddBook() {
    approveEditLoading.value = true;
    try {
        // 1. 新增书本信息
        await axios.post(
            `${BASE_URL}/api/bookData/`,
            {
                operatorId,
                userId: approveEditForm.userId,
                name: approveEditForm.name,
                desc: approveEditForm.desc,
                avatar: approveEditForm.avatar,
                isAvatar: approveEditForm.isAvatar,
                essay: approveEditForm.essay,
                bookfront1: approveEditForm.bookfront1,
                bookfront2: approveEditForm.bookfront2,
                bookPage1: approveEditForm.bookPage1,
                bookPage2: approveEditForm.bookPage2,
                bookBack: approveEditForm.bookBack,
                rotateY: approveEditForm.rotateY,
                rotateX: approveEditForm.rotateX,
                bookTop: approveEditForm.bookTop,
                bookLeft: approveEditForm.bookLeft,
                transformOrigin: approveEditForm.transformOrigin,
                color: approveEditForm.color,
                avatarTop: approveEditForm.avatarTop,
                avatarLeft: approveEditForm.avatarLeft,
                Layers: approveEditForm.Layers,
            },
            {
                headers: {
                    Authorization: "Bearer " + token,
                    "Content-Type": "application/json",
                },
            }
        );
        // 2. 更新审批状态为已通过
        await axios.put(
            `${BASE_URL}/api/approveBook/${approveRowId}`,
            {
                operatorId,
                status: "已通过",
                remark: approveEditForm.remark || "",
            },
            {
                headers: {
                    Authorization: "Bearer " + token,
                    "Content-Type": "application/json",
                },
            }
        );
        ElMessage.success("审批通过并录入成功");
        showApproveEditDialog.value = false;
        fetchBooks();
    } catch (err) {
        ElMessage.error(err.response?.data?.error || "审批或录入失败");
    } finally {
        approveEditLoading.value = false;
    }
}

// 审批（通过/拒绝）
function handleApprove() {
    loading.value = true;
    axios
        .put(
            `${BASE_URL}/api/approveBook/${approveRow.value._id}`,
            {
                operatorId,
                remark: remark.value,
                status: approveStatus.value,
            },
            {
                headers: {
                    Authorization: "Bearer " + token,
                    "Content-Type": "application/json",
                },
            }
        )
        .then((res) => {
            ElMessage.success(res.data.message);
            showDialog.value = false;
            fetchBooks();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "审批失败");
        })
        .finally(() => {
            loading.value = false;
        });
}

// 删除
function handleDelete(row) {
    axios
        .delete(`${BASE_URL}/api/approveBook/${row._id}`, {
            data: { operatorId },
            headers: {
                Authorization: "Bearer " + token,
                "Content-Type": "application/json",
            },
        })
        .then((res) => {
            ElMessage.success(res.data.message);
            fetchBooks();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "删除失败");
        });
}

onMounted(fetchBooks);
</script>

<style scoped>
.approve-book-page {
    padding: 32px 0;
    display: flex;
    justify-content: center;
}
</style>